<template>
  <div class="persistence-config">
    <a-card :bordered="false" title="Actor持久化配置">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="全局持久化">
                <a-switch 
                  v-model="globalConfig.enabled" 
                  @change="handleGlobalEnabledChange"
                  :loading="loading.global"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="持久化策略">
                <a-select 
                  v-model="globalConfig.strategy" 
                  @change="handleStrategyChange"
                  :disabled="!globalConfig.enabled"
                  style="width: 120px"
                >
                  <a-select-option value="all">全部持久化</a-select-option>
                  <a-select-option value="selective">选择性持久化</a-select-option>
                  <a-select-option value="none">不持久化</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item>
                <a-button type="primary" @click="refreshStatus" :loading="loading.refresh">
                  <a-icon type="reload" />刷新状态
                </a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 全局配置卡片 -->
      <a-card size="small" title="全局配置" style="margin-bottom: 16px">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="存储路径">
              <a-input 
                v-model="globalConfig.storagePath" 
                @blur="handleStoragePathChange"
                placeholder="data/persistence"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="快照间隔">
              <a-input-number 
                v-model="advancedConfig.snapshotInterval" 
                @change="handleAdvancedConfigChange"
                :min="100"
                :max="10000"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="事件保留数">
              <a-input-number 
                v-model="advancedConfig.eventRetentionCount" 
                @change="handleAdvancedConfigChange"
                :min="1000"
                :max="100000"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="消息黑名单">
              <a-input 
                v-model="advancedConfig.messageBlacklist" 
                @blur="handleAdvancedConfigChange"
                placeholder="HeartbeatMessage,PingMessage"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>

      <!-- Actor类型配置 -->
      <a-card size="small" title="Actor类型配置" style="margin-bottom: 16px">
        <div style="margin-bottom: 16px">
          <a-input-group compact>
            <a-input 
              v-model="newActorType.name" 
              placeholder="com.leon.datalink.node.ScheduleNodeActor"
              style="width: 60%"
            />
            <a-select v-model="newActorType.enabled" style="width: 20%">
              <a-select-option :value="true">启用</a-select-option>
              <a-select-option :value="false">禁用</a-select-option>
            </a-select>
            <a-button 
              type="primary" 
              @click="addActorType"
              :loading="loading.actorType"
              style="width: 20%"
            >
              添加
            </a-button>
          </a-input-group>
        </div>
        
        <a-table 
          :columns="actorTypeColumns" 
          :data-source="actorTypeList" 
          :pagination="false"
          size="small"
          :scroll="{ y: 200 }"
        >
          <template slot="enabled" slot-scope="text">
            <a-tag :color="text ? 'green' : 'red'">
              {{ text ? '启用' : '禁用' }}
            </a-tag>
          </template>
          <template slot="action" slot-scope="text, record">
            <a-button 
              type="link" 
              size="small" 
              @click="removeActorType(record.actorType)"
              :loading="loading.actorType"
            >
              删除
            </a-button>
          </template>
        </a-table>
      </a-card>

      <!-- 实例配置 -->
      <a-card size="small" title="Actor实例配置">
        <div style="margin-bottom: 16px">
          <a-input-group compact>
            <a-input 
              v-model="newInstance.id" 
              placeholder="node-001"
              style="width: 60%"
            />
            <a-select v-model="newInstance.enabled" style="width: 20%">
              <a-select-option :value="true">启用</a-select-option>
              <a-select-option :value="false">禁用</a-select-option>
            </a-select>
            <a-button 
              type="primary" 
              @click="addInstance"
              :loading="loading.instance"
              style="width: 20%"
            >
              添加
            </a-button>
          </a-input-group>
        </div>
        
        <a-table 
          :columns="instanceColumns" 
          :data-source="instanceList" 
          :pagination="false"
          size="small"
          :scroll="{ y: 200 }"
        >
          <template slot="enabled" slot-scope="text">
            <a-tag :color="text ? 'green' : 'red'">
              {{ text ? '启用' : '禁用' }}
            </a-tag>
          </template>
          <template slot="action" slot-scope="text, record">
            <a-button 
              type="link" 
              size="small" 
              @click="removeInstance(record.instanceId)"
              :loading="loading.instance"
            >
              删除
            </a-button>
          </template>
        </a-table>
      </a-card>

      <!-- 状态信息 -->
      <a-card size="small" title="当前状态" style="margin-top: 16px">
        <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; max-height: 300px; overflow-y: auto;">{{ statusDisplay }}</pre>
      </a-card>
    </a-card>
  </div>
</template>

<script>
import { getPersistenceStatus, updateGlobalConfig, updateActorTypeConfig, updateInstanceConfig, updateAdvancedConfig, deleteActorTypeConfig, deleteInstanceConfig } from '@/api/persistence'

export default {
  name: 'PersistenceConfig',
  data() {
    return {
      loading: {
        refresh: false,
        global: false,
        actorType: false,
        instance: false
      },
      globalConfig: {
        enabled: true,
        strategy: 'selective',
        storagePath: 'data/persistence'
      },
      advancedConfig: {
        snapshotInterval: 1000,
        eventRetentionCount: 5000,
        messageBlacklist: 'HeartbeatMessage,PingMessage'
      },
      newActorType: {
        name: '',
        enabled: true
      },
      newInstance: {
        id: '',
        enabled: true
      },
      actorTypeList: [],
      instanceList: [],
      statusDisplay: '',
      actorTypeColumns: [
        {
          title: 'Actor类型',
          dataIndex: 'actorType',
          key: 'actorType',
          width: '60%'
        },
        {
          title: '状态',
          dataIndex: 'enabled',
          key: 'enabled',
          scopedSlots: { customRender: 'enabled' },
          width: '20%'
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          width: '20%'
        }
      ],
      instanceColumns: [
        {
          title: '实例ID',
          dataIndex: 'instanceId',
          key: 'instanceId',
          width: '60%'
        },
        {
          title: '状态',
          dataIndex: 'enabled',
          key: 'enabled',
          scopedSlots: { customRender: 'enabled' },
          width: '20%'
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          width: '20%'
        }
      ]
    }
  },
  mounted() {
    this.loadStatus()
  },
  methods: {
    async loadStatus() {
      this.loading.refresh = true
      try {
        const response = await getPersistenceStatus()
        const status = response.data
        
        // 更新全局配置
        this.globalConfig.enabled = status.globalEnabled
        this.globalConfig.strategy = status.strategy
        this.globalConfig.storagePath = status.storagePath
        
        // 更新Actor类型列表
        this.actorTypeList = Object.entries(status.actorTypeConfigs || {}).map(([actorType, enabled]) => ({
          actorType,
          enabled,
          key: actorType
        }))
        
        // 更新实例列表
        this.instanceList = Object.entries(status.instanceConfigs || {}).map(([instanceId, enabled]) => ({
          instanceId,
          enabled,
          key: instanceId
        }))
        
        // 更新状态显示
        this.statusDisplay = JSON.stringify(status, null, 2)
        
        this.$message.success('状态加载成功')
      } catch (error) {
        this.$message.error('加载状态失败: ' + (error.message || '未知错误'))
        // 使用模拟数据
        this.loadMockData()
      } finally {
        this.loading.refresh = false
      }
    },
    
    loadMockData() {
      const mockStatus = {
        globalEnabled: true,
        strategy: "selective",
        storagePath: "data/persistence",
        actorTypeConfigs: {
          "com.leon.datalink.node.ScheduleNodeActor": true,
          "com.leon.datalink.rule.RuleActor": true
        },
        instanceConfigs: {
          "node-001": true,
          "node-002": false
        }
      }
      
      this.globalConfig.enabled = mockStatus.globalEnabled
      this.globalConfig.strategy = mockStatus.strategy
      this.globalConfig.storagePath = mockStatus.storagePath
      
      this.actorTypeList = Object.entries(mockStatus.actorTypeConfigs).map(([actorType, enabled]) => ({
        actorType,
        enabled,
        key: actorType
      }))
      
      this.instanceList = Object.entries(mockStatus.instanceConfigs).map(([instanceId, enabled]) => ({
        instanceId,
        enabled,
        key: instanceId
      }))
      
      this.statusDisplay = JSON.stringify(mockStatus, null, 2)
    },
    
    async refreshStatus() {
      await this.loadStatus()
    },
    
    async handleGlobalEnabledChange(enabled) {
      await this.updateGlobalConfig({ globalEnabled: enabled })
    },
    
    async handleStrategyChange(strategy) {
      await this.updateGlobalConfig({ strategy })
    },
    
    async handleStoragePathChange() {
      await this.updateGlobalConfig({ storagePath: this.globalConfig.storagePath })
    },
    
    async updateGlobalConfig(config) {
      this.loading.global = true
      try {
        const fullConfig = {
          globalEnabled: this.globalConfig.enabled,
          strategy: this.globalConfig.strategy,
          storagePath: this.globalConfig.storagePath,
          ...config
        }
        
        await updateGlobalConfig(fullConfig)
        this.$message.success('全局配置更新成功')
        await this.loadStatus()
      } catch (error) {
        this.$message.error('更新失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading.global = false
      }
    },
    
    async handleAdvancedConfigChange() {
      try {
        await updateAdvancedConfig(this.advancedConfig)
        this.$message.success('高级配置更新成功')
      } catch (error) {
        this.$message.error('更新失败: ' + (error.message || '未知错误'))
      }
    },
    
    async addActorType() {
      if (!this.newActorType.name.trim()) {
        this.$message.warning('请输入Actor类型')
        return
      }
      
      this.loading.actorType = true
      try {
        await updateActorTypeConfig({
          actorType: this.newActorType.name,
          enabled: this.newActorType.enabled
        })
        
        this.$message.success('Actor类型配置添加成功')
        this.newActorType.name = ''
        this.newActorType.enabled = true
        await this.loadStatus()
      } catch (error) {
        this.$message.error('添加失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading.actorType = false
      }
    },
    
    async removeActorType(actorType) {
      this.loading.actorType = true
      try {
        await deleteActorTypeConfig(actorType)

        this.$message.success('Actor类型配置删除成功')
        await this.loadStatus()
      } catch (error) {
        this.$message.error('删除失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading.actorType = false
      }
    },
    
    async addInstance() {
      if (!this.newInstance.id.trim()) {
        this.$message.warning('请输入实例ID')
        return
      }
      
      this.loading.instance = true
      try {
        await updateInstanceConfig({
          instanceId: this.newInstance.id,
          enabled: this.newInstance.enabled
        })
        
        this.$message.success('实例配置添加成功')
        this.newInstance.id = ''
        this.newInstance.enabled = true
        await this.loadStatus()
      } catch (error) {
        this.$message.error('添加失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading.instance = false
      }
    },
    
    async removeInstance(instanceId) {
      this.loading.instance = true
      try {
        await deleteInstanceConfig(instanceId)

        this.$message.success('实例配置删除成功')
        await this.loadStatus()
      } catch (error) {
        this.$message.error('删除失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading.instance = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.persistence-config {
  .table-page-search-wrapper {
    margin-bottom: 16px;
  }
  
  .ant-card {
    margin-bottom: 0;
  }
  
  .ant-form-item {
    margin-bottom: 8px;
  }
  
  pre {
    font-size: 12px;
    line-height: 1.4;
  }
}
</style>
